<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户名" prop="account">
        <el-input v-model="queryParams.account" placeholder="请输入用户名" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdatePassword">修改密码</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="userList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="头像" width="80" align="center">
        <template slot-scope="scope">
          <el-image v-if="scope.row.image" :src="getImageUrl('https://oss.ptyxlm.cn/' + scope.row.image)" fit="cover"
            class="avatar-image" :preview-src-list="[getImageUrl('https://oss.ptyxlm.cn/' + scope.row.image)]" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="account" min-width="120" show-overflow-tooltip />
      <el-table-column label="姓名" prop="name" min-width="120" show-overflow-tooltip />
      <el-table-column label="手机号" prop="phone" width="130" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="mail" min-width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.mail || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.age !== undefined && scope.row.age !== null ? scope.row.age : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="sex" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ getSexLabel(scope.row.sex) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="tag_name" width="120" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.tag_name" size="mini" type="info">{{ scope.row.tag_name }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否实名" prop="isReal" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isReal ? 'success' : 'info'">{{ scope.row.isReal ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否志愿者" prop="is_volunteer" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_volunteer ? 'success' : 'info'">{{ scope.row.is_volunteer ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdAt" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt ? parseTime(scope.row.createdAt) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdatePassword(scope.row)">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="500px" append-to-body>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入旧密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="passwordForm.confirm_password" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="passwordForm.captcha" placeholder="请输入验证码" style="width: 60%"
            @keyup.enter.native="submitPasswordForm" />
          <div class="captcha-img" @click="getCaptcha">
            <img :src="captchaUrl" alt="验证码" class="captcha-image" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="passwordSubmitLoading" @click="submitPasswordForm">确 定</el-button>
        <el-button @click="cancelPassword">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, updateUserPassword } from '@/api/api'
import { getCodeImg } from '@/api/login'

export default {
  name: 'User',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.new_password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      passwordSubmitLoading: false,
      showSearch: true,
      userList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      passwordDialogVisible: false,
      captchaUrl: '',
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        page: 1,
        pageSize: 10,
        account: undefined,
        name: undefined,
        phone: undefined
      },
      passwordForm: {
        id: undefined,
        username: '',
        old_password: '',
        new_password: '',
        confirm_password: '',
        captcha: ''
      },
      passwordRules: {
        old_password: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        new_password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirm_password: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getUserList(this.queryParams)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.userList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },
    handleUpdatePassword(row) {
      const targetId = row?.id ?? this.ids[0]
      if (!targetId) {
        this.$modal.msgWarning('请选择要修改密码的用户')
        return
      }
      const record = this.userList.find(item => String(item.id) === String(targetId))
      if (!record) {
        this.$modal.msgWarning('未找到对应用户数据')
        return
      }
      this.passwordForm = {
        id: record.id,
        username: record.account || record.name || `用户${record.id}`,
        old_password: '',
        new_password: '',
        confirm_password: '',
        captcha: ''
      }
      this.getCaptcha()
      this.$nextTick(() => {
        if (this.$refs.passwordForm && this.$refs.passwordForm.clearValidate) {
          this.$refs.passwordForm.clearValidate()
        }
      })
      this.passwordDialogVisible = true
    },
    getCaptcha() {
      getCodeImg().then(res => {
        if (res.data) {
          // 如果返回的是base64数据，直接使用
          if (typeof res.data === 'string' && res.data.startsWith('data:image')) {
            this.captchaUrl = res.data
          } else if (typeof res.data === 'string') {
            // 如果不是base64格式，添加前缀
            this.captchaUrl = 'data:image/gif;base64,' + res.data
          } else if (res.img) {
            // 兼容其他可能的字段名
            this.captchaUrl = 'data:image/gif;base64,' + res.img
          }
        } else if (res.img) {
          this.captchaUrl = 'data:image/gif;base64,' + res.img
        }
      }).catch(() => {
        this.$modal.msgError('获取验证码失败')
      })
    },
    submitPasswordForm() {
      this.$refs.passwordForm.validate(valid => {
        if (!valid) {
          return
        }
        this.passwordSubmitLoading = true
        const payload = {
          old_password: this.passwordForm.old_password,
          new_password: this.passwordForm.new_password,
          captcha: this.passwordForm.captcha
        }
        // 如果有用户ID，可以添加到请求中（如果需要）
        if (this.passwordForm.id) {
          payload.id = this.passwordForm.id
        }
        updateUserPassword(payload)
          .then(() => {
            this.$modal.msgSuccess('密码修改成功')
            this.passwordDialogVisible = false
            this.resetPasswordForm()
            // 如果是修改当前登录用户的密码，可能需要重新登录
          })
          .catch(() => {
            // 修改失败时刷新验证码
            this.getCaptcha()
            this.passwordForm.captcha = ''
          })
          .finally(() => {
            this.passwordSubmitLoading = false
          })
      })
    },
    cancelPassword() {
      this.passwordDialogVisible = false
      this.resetPasswordForm()
    },
    resetPasswordForm() {
      this.passwordForm = {
        id: undefined,
        username: '',
        old_password: '',
        new_password: '',
        confirm_password: '',
        captcha: ''
      }
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.resetFields()
      }
    },
    getStatusLabel(value) {
      if (value === 1 || value === '1') {
        return '启用'
      }
      if (value === 0 || value === '0' || value === 2 || value === '2') {
        return '禁用'
      }
      return '-'
    },
    getStatusTagType(value) {
      if (value === 1 || value === '1') {
        return 'success'
      }
      if (value === 0 || value === '0' || value === 2 || value === '2') {
        return 'danger'
      }
      return 'default'
    },
    getSexLabel(value) {
      if (value === 1 || value === '1') {
        return '男'
      }
      if (value === 0 || value === '0' || value === 2 || value === '2') {
        return '女'
      }
      return '-'
    },
    getImageUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) {
        return url
      }
      if (this.baseUrl && url.startsWith(this.baseUrl)) {
        return url
      }
      if (this.baseUrl) {
        const prefix = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl
        const path = url.startsWith('/') ? url : `/${url}`
        return `${prefix}${path}`
      }
      return url
    }
  }
}
</script>

<style scoped lang="scss">
.captcha-img {
  display: inline-block;
  width: 35%;
  height: 38px;
  margin-left: 5%;
  vertical-align: middle;
  cursor: pointer;

  .captcha-image {
    width: 100%;
    height: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  &:hover .captcha-image {
    border-color: #c0c4cc;
  }
}

.avatar-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}
</style>
